<template>
  <Dialog
    v-model:show="showAssociationPortalDialog"
    width="100vw"
    height="100vh"
    :title="config.modal.data[config.nameColumn]"
    no-header
    z-index="100"
  >
    <template #dialog-body>
      <van-tabs v-model:active="activeTab" :ellipsis="false" class="association-tabs">
        <van-tab v-for="(tab, index) in bindTabs" :key="index" :title="tab.title" :name="tab.tableId">
          <PortalData
            is-association
            :table-id="tab.tableId"
            :default-sort-column="tab.defaultSortColumn"
            :external-search-condition="getSearchCondition(tab)"
          />
        </van-tab>
      </van-tabs>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import Dialog from '@/framework/components/Dialog/index.vue'
import { usePassVar } from '@/framework/hooks/usePassVar'
import PortalData from '@/framework/components/PortalData/index.vue'
import { PortalBindType } from '@/framework/components/PortalData/types'
import { ConditionListType, FILTER_TYPE } from '@/framework/types/portal.d'

const props = defineProps<{
  show: boolean
  config: any
  bindTabs: Array<PortalBindType>
}>()

const { config, bindTabs } = toRefs(props)

watch(
  () => bindTabs.value,
  () => {
    console.log(bindTabs.value)
  }
)

const getSearchCondition = (tab: any) => {
  const { data } = config.value.modal
  const rowKey = config.value.idColumn
  const { bindType, bindFieldProperty, defaultAdvancedCondition } = tab
  let condition = {} as ConditionListType
  if (bindType === '0') {
    condition = {
      property: bindFieldProperty,
      relation: FILTER_TYPE.EQUAL,
      value: [data[rowKey]]
    } as ConditionListType
  } else if (bindType === '3') {
    condition = {
      property: bindFieldProperty,
      relation: FILTER_TYPE.CONTAIN,
      value: [data[rowKey]]
    } as ConditionListType
  } else if (bindType === '1') {
    condition = {
      property: bindFieldProperty,
      relation: FILTER_TYPE.EQUAL,
      value: [data[bindFieldProperty]]
    } as ConditionListType
  } else if (bindType === '4') {
    condition = {
      property: bindFieldProperty,
      relation: FILTER_TYPE.CONTAIN,
      value: [data[bindFieldProperty]]
    } as ConditionListType
  }
  const searchCondition = [condition]
  if (defaultAdvancedCondition) searchCondition.push(defaultAdvancedCondition)
  return searchCondition
}

let activeTab = ref(0)

const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
}>()

let showAssociationPortalDialog = ref(false)

usePassVar(props, 'show', showAssociationPortalDialog)

watch(
  () => showAssociationPortalDialog.value,
  () => emit('update:show', showAssociationPortalDialog.value)
)
</script>

<style scoped>
.association-tabs {
  margin-top: 8.5vh;
}
</style>
